package com.detrum.service;

import android.app.AppOpsManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.IBinder;
import android.support.v4.app.NotificationManagerCompat;
import android.text.style.TtsSpan;


import com.detrum.DownloadReceiver;
import com.detrum.base.BaseStatic;
import com.detrum.base.R;
import com.detrum.bean.VersionBean;
import com.detrum.sqlite.SqliteVersionOperate;
import com.detrum.utils.LogUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;


public class DownloadDeviceService extends Service {
    private String TAG="DownloadDeviceService";
    private String name;
    private Notification.Builder builder;
    private NotificationManager manager;
    private int notifyId=4;
    private boolean isenable;

    @Override
    public void onCreate() {
        super.onCreate();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(BaseStatic.deviceNetPath==null||BaseStatic.deviceNetPath.length()==0){
            return Service.START_STICKY_COMPATIBILITY;
        }
        String[]strs = BaseStatic.deviceNetPath.split("/");
        name = strs[strs.length-1];
        LogUtils.e("DownloadDeviceService BaseStatic.deviceName = "+BaseStatic.deviceName);
        isenable = NotificationManagerCompat.from(this).areNotificationsEnabled();
        if(isenable){
            builder = new Notification.Builder(this.getApplicationContext());
            manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if(BaseStatic.deviceName.equals("IWT-AGS58")){
                builder.setSmallIcon(R.mipmap.mslogo3);
            }else if(BaseStatic.deviceName.equals("DCAM-H")){
                builder.setSmallIcon(R.mipmap.sport2);
            }else{
                builder.setSmallIcon(R.mipmap.ic_launcher);
            }
            builder.setContentTitle(name);
            builder.setOngoing(true);
            builder.setPriority(Notification.PRIORITY_DEFAULT);
            manager.notify(notifyId,builder.build());
        }
        LogUtils.i("isenable = "+isenable);

        myTask=new MyTask();
        myTask.execute();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private MyTask myTask;

    private File file,fileTemp;
    private int length;//文件长度
    class MyTask extends AsyncTask<Void,Integer,File> {

        @Override
        protected void onPostExecute(final File s) {
            super.onPostExecute(s);
            //下载完成
            if(s!=null){
                Intent intent1=new Intent("downloadDevice");
                intent1.putExtra("path",file.getPath());
                sendBroadcast(intent1);
                LogUtils.i("sendBroadcast ----- 下载完成");
            }else{
                Intent intent3 = new Intent("downloadFail");
                sendBroadcast(intent3);
                LogUtils.i("sendBroadcast ----- 下载失败");
            }
            if(manager!=null){
                manager.cancel(notifyId);
            }

        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            Intent intent2=new Intent("downloadDevice");
            intent2.putExtra("length",length);
            intent2.putExtra("progress",values[0]);
            sendBroadcast(intent2);
        }

        @Override
        protected File doInBackground(Void... params) {
            //判断本地更新文件是否存在
            file=new File(BaseStatic.path,name);
            if(file.exists()&&file.length()!=0){
                //判断本地更新文件校验码是否正确
                String fileMd5 = getFileMD5(file);
                LogUtils.i("fileMd5 = "+fileMd5+"\nNetVerify = "+BaseStatic.deviceNetVerify);
                if(fileMd5.equals(BaseStatic.deviceNetVerify)){
                    VersionBean bean = new VersionBean();
                    bean.setLocalFilePath(file.getPath());
                    bean.setName(BaseStatic.deviceName);
                    SqliteVersionOperate.getInstance(DownloadDeviceService.this).Insert(bean);
                    if(manager!=null){
                        manager.cancel(notifyId);
                    }
                    return file;
                }else{
                    file.delete();//校验错误删除文件
                }
            }
            //创建临时路径下载更新文件
            try {
                File file1=new File(BaseStatic.path);
                if(!file1.exists()){
                    file1.mkdirs();
                }
                if(BaseStatic.deviceNetPath==null){
                    return null;
                }
                fileTemp=new File(BaseStatic.path,name+".det");
                FileOutputStream fos=new FileOutputStream(fileTemp);
                BaseStatic.savaInfoToSD("DownloadDeviceService url==="+BaseStatic.deviceNetPath);
                LogUtils.i("DownloadDeviceService url==="+BaseStatic.deviceNetPath);
                URL url=new URL(BaseStatic.deviceNetPath);
                HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
                httpURLConnection.connect();
                length = httpURLConnection.getContentLength();

                if(isenable){
                    builder.setProgress(length,0,false);
                    builder.setOngoing(true);
                    manager.notify(notifyId,builder.build());
                }

                InputStream is=httpURLConnection.getInputStream();
                int x=0,y=0;
                byte[] b=new byte[1024];
                while ((x=is.read(b,0,1024))!=-1){
                    fos.write(b,0,x);
                    y+=x;
                    if(isenable){
                        builder.setProgress(length,y,false);
                        builder.setContentText("下载"+y*100/length+"%");
                        builder.setOngoing(true);
                        manager.notify(notifyId,builder.build());
                        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT){
                            publishProgress(y);
                        }
                    }else{
                        publishProgress(y);
                    }
                }
                fos.flush();
                if(is!=null){
                    is.close();
                }
                if(fos!=null){
                    fos.close();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //验证下载文件的完整性
            LogUtils.e("deviceNetLength = "+BaseStatic.deviceNetLength+"   fileLength = "+fileTemp.length());
            BaseStatic.savaInfoToSD("deviceNetLength = "+BaseStatic.deviceNetLength+"   fileLength = "+file.length());
            if(fileTemp.length()==length){
                file = new File(BaseStatic.path,name);
                fileTemp.renameTo(file);
            }
            //验证下载文件的md5码和长度
            // TODO: 2018/5/17 失败检测
            String fileMd5 = getFileMD5(file);
            //String fileMd5 = "asdggh";
            LogUtils.e("deviceNetVerify = "+BaseStatic.deviceNetVerify+"   fileMd5 = "+fileMd5);
            BaseStatic.savaInfoToSD("deviceNetVerify = "+BaseStatic.deviceNetVerify+"   fileMd5 = "+fileMd5);
            if(file.length()!=BaseStatic.deviceNetLength||!fileMd5.equals(BaseStatic.deviceNetVerify)){
                file.delete();
                return null;
            }
            VersionBean bean = new VersionBean();
            bean.setLocalFilePath(file.getPath());
            bean.setName(BaseStatic.deviceName);
            SqliteVersionOperate.getInstance(DownloadDeviceService.this).Insert(bean);
            return file;
        }
    }

    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[10240];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 10240)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(16);
       //return bytesToHexString(digest.digest());
    }

    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
}
